# -*- coding: utf-8 -*-
# ----------------------------
# @Time    : 2022/6/4 12:41 PM
# @Author  : changqingai
# @FileName: tf_critical_section.py
# ----------------------------

import tensorflow as tf
from tensorflow import CriticalSection
from tensorflow import Graph

v = tf.compat.v1.get_variable("v", initializer=0.0, use_resource=True)
def accumulate(up=1):
  x = v.read_value()
  with tf.control_dependencies([x]):
    with tf.control_dependencies([v.assign_add(up)]):
      return tf.identity(x)
ex1 = CriticalSection().execute(
  accumulate, exclusive_resource_access=False)
ex2 = CriticalSection().execute(
  accumulate, exclusive_resource_access=False)
bad_sum = ex1 + ex2

sess = tf.compat.v1.Session()
sess.run(v.initializer)
sess.run(bad_sum)  # May return 0.0
print()

tf.t